package fun.tan90.easy.binlog.worker.handler;

import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.zaxxer.hikari.HikariDataSource;
import fun.tan90.easy.binlog.base.constants.EasyBinlogConstants;
import fun.tan90.easy.binlog.base.strategy.AbstractExecuteStrategy;
import fun.tan90.easy.binlog.worker.cache.DataSourceKey;
import lombok.extern.slf4j.Slf4j;
import org.noear.socketd.transport.core.Message;
import org.noear.socketd.transport.core.entity.StringEntity;
import org.springframework.stereotype.Component;

import java.util.Objects;

/**
 * description TODO
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2023/12/15 19:42
 */
@Slf4j
@Component
public class MasterVersionHandler implements AbstractExecuteStrategy<Message, org.noear.socketd.transport.core.Entity> {

    @Override
    public String mark() {
        return EasyBinlogConstants.MASTER_VERSION;
    }

    @Override
    public org.noear.socketd.transport.core.Entity executeResp(Message message) {
        String masterCode = message.dataAsString();
        HikariDataSource dataSource = DataSourceKey.getDataSource(masterCode);
        if (Objects.isNull(dataSource)) {
            return new StringEntity("");
        }
        if (dataSource.isClosed()) {
            return new StringEntity("");
        }
        try {
            Entity entity = Db.use(dataSource).queryOne("select version() as version");
            return new StringEntity(entity.getStr("version"));
        } catch (Exception e) {
            log.error(e.getMessage());
        }
        return new StringEntity("");
    }
}
